from PySide6.QtWidgets import (
    QVBoxLayout, QHBoxLayout, QGroupBox, QLabel, 
    QInputDialog, QSizePolicy, QLineEdit
)
from PySide6.QtCore import Qt
from PySide6.QtCore import QTimer

from .base_module import BaseModule
from .components.switch_widget import SwitchWidget
from presenter.setting_presenter import SettingPresenter


class SettingModule(BaseModule):
    """设置模块"""
    need_server_widget = False
    def __init__(self, server_manager=None):
        super().__init__()
        self.setting_pr = SettingPresenter(self, server_manager)
        self.module_enabled = self.setting_pr.status  
        self.setup_ui()        
        
        QTimer.singleShot(0, lambda: self.bus.emit("mode_change", self.module_enabled))  

    def setup_ui(self):
        main_group = QGroupBox("功能开关")

        switch_row = QHBoxLayout()

        # 左侧文字
        text_layout = QVBoxLayout()
        title = QLabel("软件包校验/部署")
        title.setObjectName("setting_title") 
        desc = QLabel("控制软件包上传、命令输入、执行命令等功能")
        desc.setObjectName("setting_desc") 
        text_layout.addWidget(title)
        text_layout.addWidget(desc)
        switch_row.addLayout(text_layout)
        switch_row.addStretch()

        # 右侧状态+开关
        row_layout = QVBoxLayout()
        row_layout.setAlignment(Qt.AlignRight)
        row_layout.setSpacing(6)

        self.switch = SwitchWidget()
        self.switch.setChecked(self.module_enabled)
        self.switch.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.switch.toggled.connect(self.on_switch_clicked)
        row_layout.addWidget(self.switch, alignment=Qt.AlignHCenter)

        switch_row.addLayout(row_layout)
        main_group.setLayout(switch_row)
        self.layout.addWidget(main_group)
        self.layout.addStretch()

    def on_switch_clicked(self, checked):
        """开关点击事件"""
        if checked:
            password, ok = QInputDialog.getText(
                self, "密码验证", "密码:", echo=QLineEdit.Password
            )
            if ok and password and self.setting_pr.handle_pwd(password):
                self.ToastWidget(self, "功能已启用")
                self.emit("mode_change", True)
            else:
                self.switch.setChecked(False)
                if ok:
                    self.ToastWidget(self, "密码错误")
                self.emit("mode_change", False)
        else:
            self.ToastWidget(self, "功能已关闭")
            self.emit("mode_change", False)

